package org.dizem.freepl0.compiler.tablemanager;

import org.dizem.freepl0.compiler.FPCompiler;

/**
 * Created by IntelliJ IDEA.
 * User: DIZEM
 * Date: 11-2-2
 * Time: 下午3:06
 */
public class TableManager {
	public static int TABLE_SIZE = 100;

	public int getTableIndex() {
		return tx[level];
	}

	private Table[] table = new Table[TABLE_SIZE];
	private int[] tx = new int[4];
	private int level;
	private FPCompiler compiler;

	public TableManager(FPCompiler compiler) {
		this.compiler = compiler;
		for (int i = 0; i < TABLE_SIZE; ++i)
			table[i] = new Table();
	}


	public void Enter(TableType type) {
		if (compiler.getGrammaAnalysis().getLevel() > level)
			tx[++level] = tx[level - 1];
		else if (compiler.getGrammaAnalysis().getLevel() < level)
			level--;
		tx[level]++;
		if (tx[level] >= TABLE_SIZE)
			return;

		table[tx[level]].setName(compiler.getWordAnalysis().getWord());
		table[tx[level]].setType(type);

		switch (type) {
			case CONSTANT:
				table[tx[level]].setVal(compiler.getWordAnalysis().num);
				break;

				case VARIABLE:
				table[tx[level]].setLevel(compiler.getGrammaAnalysis().getLevel());
				table[tx[level]].setAddress(compiler.getGrammaAnalysis().getDataAddress());
				break;

			case PROCEDURE:
				table[tx[level]].setLevel(compiler.getGrammaAnalysis().getLevel());
				break;
		}
	}

	public int Position(String id) {
		int i = tx[level];
		while (!table[i].getName().equals(id) && i > 0)
			i--;
		return i;
	}

	public Table[] getTable() {
		return table;
	}
};
